
/**
 * 入参处理sql参数
*/
class Parameters {
  constructor(props) {
    this.props = props
    this.keys = []
    this.values = []
    this.num = ''
    this.updateData = []
    this.handle(props)
  }
  init() {
    this.keys = []
    this.values = []
    this.num = []
  }
  handle(DATA) {
    this.init()
    // console.log(DATA.content, '_________');
    Object.keys(DATA).forEach(ele => {
      this.keys.push(ele)
      this.values.push(DATA[ele])
      this.num.push('?')
    })
    this.keys = this.keys.toString()
    this.num = this.num.toString()
    return this
  }
  add(v) {
    if (typeof v === 'object') {
      this.props = { ...this.props, ...v }
    }
    if (typeof v === 'function') {
      const _ = v(this.props)
      this.props = { ...this.props, ..._ }
    }
    this.handle(this.props)
    return this
  }
  del(v) {
    const DATA = { ...this.props }
    if (typeof v === 'string') {
      delete DATA[v]
    } else {
      v.forEach(ele => {
        delete DATA[ele]
      })
    }
    this.handle(DATA)
    return this
  }
  update(arr) {
    arr.forEach(ele => {
      this.updateData.push(this.props[ele])
    })
    return this
  }
}

/**
 * 表联查对别名字段进行过滤返回
 * @data sql返回的数据
 * @rules 需要用什么开头匹配
 * @callback(res)=> 处理完执行的回调 res是处理好的数据
*/
function handlingAliases(data, rules, callback) {
  if (!data?.length) return callback([], {})
  const arr = []//符合过滤规则的
  const arr1 = []//不符合过滤规则的
  data.forEach(ele => {
    let obj = {}//符合规则的
    let obj1 = {}//不符合规则的
    for (const key in ele) {
      if (key.substr(0, rules.length) === rules) {
        obj[key.replace(rules, '')] = ele[key]
      } else {
        obj1[key] = ele[key]
      }
    }
    arr.push(obj)
    arr1.push(obj1)
  })
  callback(arr, arr1[0] || {})
}
/**
 * 字段名 : 字段的含义
 * 进行非空校验
*/
const fieldDesc = (config, data, res, callback) => {
  const arr = Object.keys(config)
  let status = true
  for (let i = 0; i < arr.length; i++) {
    const ele = arr[i];
    if (!data[ele]) {
      res.sendError(null, config[ele] + '不能为空')
      status = false
      break
    }
  }
  if (status) callback && callback()
}

function generateInsertSQL(tableName, data) {
  const columns = Object.keys(data).join(', ');
  const values = Object.values(data)
    .map(value => {
      if (typeof value === 'string') {
        // 转义单引号以防止SQL注入
        return `'${value.replace(/'/g, "''")}'`;
      }
      return value;
    })
    .join(', ');

  return `INSERT INTO ${tableName} (${columns}) VALUES (${values});`;
}
const uuid = () => {
  return 'id-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
}
// 使用示例
// const tableName = 'users';
// const data = {
//   name: 'John Doe',
//   email: 'john.doe@example.com',
//   age: 30
// };
module.exports = { Parameters, fieldDesc, handlingAliases, generateInsertSQL, uuid }
